package com.app.newcsc.fragment.main;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.app.newcsc.BR;
import com.app.newcsc.R;
import com.app.newcsc.app.AppApplication;
import com.app.newcsc.app.AppViewModelFactory;
import com.app.newcsc.databinding.FragmentTabTransactionTabBinding;
import com.app.newcsc.entity.Message;
import com.app.newcsc.entity.PayAccountEntity;
import com.app.newcsc.entity.WalletEntity;
import com.app.newcsc.fragment.my.safe.SafeFragment;
import com.app.newcsc.utils.NumberUtils;
import com.app.newcsc.utils.SpUtils;
import com.app.newcsc.utils.TextUtil;
import com.app.newcsc.utils.ToastUtil;
import com.app.newcsc.utils.Utils;
import com.app.newcsc.view.CustomPopWindow;
import com.app.newcsc.viewmodel.TransactionTabItemViewModel;
import com.app.newcsc.viewmodel.TransactionTabViewModel;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter;

/**
 * @author: woking
 * @date: 2021/6/7
 * @description：
 */
public class TransactionTabFragment extends BaseFragment<FragmentTabTransactionTabBinding, TransactionTabViewModel> {

    private String type = "";
    private Disposable mSubscription;
    private int  mAuthentication = -1;

    public static TransactionTabFragment newInstance(String invitationType,String time) {
        TransactionTabFragment fragment = new TransactionTabFragment();
        Bundle args = new Bundle();
        args.putString("Type", invitationType);
        args.putString("time", time);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initParam() {
        super.initParam();
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_tab_transaction_tab;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public TransactionTabViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用NetWorkViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(TransactionTabViewModel.class);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mSubscription != null)
        {
            RxSubscriptions.remove(mSubscription);
        }
        if(mCustomPopWindow != null)
        {
            mCustomPopWindow.dissmiss();
        }
    }

    @Override
    public void initData() {
        if (getArguments() != null) {
            type = getArguments().getString("Type");
            viewModel.type.setValue(type);
            String time = getArguments().getString("time");
            binding.openTime.setText(time);
        }
        viewModel.isBuy.setValue(true);

//        RxBus.getDefault().post(new DownLoadStateBean(contentLength(), bytesReaded, tag));
        mSubscription = RxBus.getDefault().toObservable(Message.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(new Consumer<Message>() {
                    @Override
                    public void accept(final Message message) throws Exception {
//                        Log.e("TAG",type + "===============message====HTTP=========="+message.getName());
                        boolean isUpload = false;
                        if(viewModel.isBuy.getValue() && message.getName().equals("sell"))
                        {
                            isUpload = true;
                        }
                        else if(!viewModel.isBuy.getValue() && message.getName().equals("buy"))
                        {
                            isUpload = true;
                        }
                        if(message.getName().equals("buy"))
                        {
                            viewModel.isBuy.setValue(true);
                        }
                        else if(message.getName().equals("sell"))
                        {
                            viewModel.isBuy.setValue(false);
                        }
                        isFirstLoad = true;
//                        Log.e("TAG",isUpload + "=====isUpload==========message====HTTP======type===="+type + "  message.getType():" + message.getData());
                        if (isUpload && type.equals(message.getData()))
                        {
                            showDialog("");
                            //请求网络数据
//                            viewModel.requestNetWork(false);
                            binding.twinklingRefreshLayout.autoRefresh();
                            isFirstLoad = false;
                        }
                    }
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);

        binding.myrecyclerview.setEmptyView(binding.emptyView);
        //给RecyclerView添加Adpter，请使用自定义的Adapter继承BindingRecyclerViewAdapter，重写onBindBinding方法，里面有你要的Item对应的binding对象。
        // Adapter属于View层的东西, 不建议定义到ViewModel中绑定，以免内存泄漏
        binding.setAdapter(new BindingRecyclerViewAdapter());

//      showDialog("");
//      //请求网络数据
//      viewModel.requestNetWork(false);
//      isLoad = false;


        initRefreshLayout();

        viewModel.isreflsh.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(anquanYanzhengPopWindow != null)
                {
                    anquanYanzhengPopWindow.dissmissNoRecovery();
                }
//                viewModel.requestNetWork(false);
                binding.twinklingRefreshLayout.autoRefresh();
            }
        });
    }
    public boolean isFirstLoad = true;
    @Override
    public void onResume() {
        super.onResume();
//        Log.e("TAG","============onResume======HTTP======");
        if (isFirstLoad)
        {
            // 将数据加载逻辑放到onResume()方法中
            showDialog("");
            //请求网络数据
//            viewModel.requestNetWork(false);
            binding.twinklingRefreshLayout.autoRefresh();
            isFirstLoad = false;
        }
    }

    private void initRefreshLayout()
    {
        binding.twinklingRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                viewModel.onRefresh();
            }
        });
        binding.twinklingRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.onLoadMore();
            }
        });
//        binding.twinklingRefreshLayout.autoRefresh();
    }

    @Override
    public void initViewObservable() {
        //监听下拉刷新完成
        viewModel.uc.finishRefreshing.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
//                binding.twinklingRefreshLayout.finishRefreshing();
                binding.twinklingRefreshLayout.finishRefresh();
                dismissDialog();
            }
        });
        //监听上拉加载完成
        viewModel.uc.finishLoadmore.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
//                binding.twinklingRefreshLayout.finishLoadmore();
                binding.twinklingRefreshLayout.finishLoadMore();
//                binding.twinklingRefreshLayout.finishLoadMoreWithNoMoreData();//没有更多数据了
            }
        });
        viewModel.mPayAccountEntitys.observe(this, new Observer<List<PayAccountEntity>>() {
            @Override
            public void onChanged(List<PayAccountEntity> payAccountEntities) {

                String payType = "";
                for(PayAccountEntity entity : payAccountEntities)
                {
                    payType = payType + entity.type;
                }

                boolean isOk = false;
                List<String> pay_types = viewModel.buySellItemLiveData.getValue().entity.get().pay_types;
                for(String str : pay_types)
                {
                    if(payType.contains(str))
                    {
                        isOk = true;
                        break;
                    }
                }
                if(isOk)
                {
                    initPop(binding.contentLl,viewModel.buySellItemLiveData.getValue());
                }
                else
                {
                    ToastUtil.showToast("请添加支付方式");
                }
            }
        });
        viewModel.buySellItemLiveData.observe(this, new Observer<TransactionTabItemViewModel>() {
            @Override
            public void onChanged(TransactionTabItemViewModel transactionTabItemViewModel) {
                if(!Utils.isLogin())
                {
                    return;
                }
                Log.e("TAG", transactionTabItemViewModel.getPosition()+"=============onClickBuySell=================");

//                if(!viewModel.isBuy.getValue())
//                {
//                    viewModel.otcPayCccount();
////                    if(viewModel.mPayAccountEntitys == null || viewModel.mPayAccountEntitys.getValue() == null || viewModel.mPayAccountEntitys.getValue().size() < 1)
////                    {
////                        viewModel.otcPayCccount();
////                    }
////                    else
////                    {
////                        String payType = "";
////                        for(PayAccountEntity entity : viewModel.mPayAccountEntitys.getValue())
////                        {
////                            payType = payType + entity.type;
////                        }
////
////                        boolean isOk = false;
////                        List<String> pay_types = transactionTabItemViewModel.entity.get().pay_types;
////                        for(String str : pay_types)
////                        {
////                            if(payType.contains(str))
////                            {
////                                isOk = true;
////                                break;
////                            }
////                        }
////                        if(isOk)
////                        {
////                            initPop(binding.contentLl,viewModel.buySellItemLiveData.getValue());
////                        }
////                        else
////                        {
////                            ToastUtil.showToast("请添加支付方式");
////                        }
////                    }
//                }
//                else{
//                    initPop(binding.contentLl,transactionTabItemViewModel);
//                }
                initPop(binding.contentLl,transactionTabItemViewModel);
            }
        });
    }

    private CustomPopWindow mCustomPopWindow;
    private void initPop(View view,TransactionTabItemViewModel model)
    {
        mAuthentication = SpUtils.getInt(getActivity(),"authentication");
        if (mAuthentication!=1){
            if (mAuthentication == 0){
                ToastUtil.showToast("请先进行实名认证");
            }else if (mAuthentication == 2){
                ToastUtil.showToast("您提交的实名认证失败，请重新认证");
            }else if (mAuthentication == 3){
                ToastUtil.showToast("您提交的实名认证正在审核，请耐心等待");
            }
            return;
        }
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.pop_buy_csc,null);
        TextView price_tv = contentView.findViewById(R.id.price_tv);//单价
        TextView title_tv = contentView.findViewById(R.id.title_tv);//单价
        title_tv.setText(viewModel.isBuy.getValue() ? "购买CSC" : "转赠CSC");
        price_tv.setText(AppApplication.pricetag + model.entity.get().price);//"￥" + model.entity.get().price
        EditText num_et = contentView.findViewById(R.id.num_et);//数量
        num_et.setText(model.entity.get().num);
        TextView shouxufei_value_tv = contentView.findViewById(R.id.shouxufei_value_tv);//手续费
        shouxufei_value_tv.setText(model.entity.get().free_ratio+"%");
        TextView keyong_tv = contentView.findViewById(R.id.keyong_tv);//可用
        TextView shishoukuan_tv = contentView.findViewById(R.id.shishoukuan_tv);//实收款
        shishoukuan_tv.setText(model.entity.get().num + "CSC");
        TextView shizhichu_tv = contentView.findViewById(R.id.shizhichu_tv);//实付款
//        shizhichu_tv.setText(AppApplication.pricetag +//"￥" +
//                (Double.parseDouble(model.entity.get().num) *
//                        Double.parseDouble(model.entity.get().price)));

        shizhichu_tv.setText(AppApplication.pricetag +//"￥" +
                NumberUtils.keepPrecision((Double.parseDouble(model.entity.get().num) *
                        Double.parseDouble(model.entity.get().price)),4));

        TextView shishoukuan_key_tv = contentView.findViewById(R.id.shishoukuan_key_tv);//单价
        TextView shizhichu_key_tv = contentView.findViewById(R.id.shizhichu_key_tv);//单价
        if(viewModel.isBuy.getValue())
        {
            shishoukuan_key_tv.setText("实收款");
            shizhichu_key_tv.setText("实支出");
        }
        else
        {
            shishoukuan_key_tv.setText("实支出");
            shizhichu_key_tv.setText("实收款");
        }

        if(getWalletEntityType("CSC") != null)
        {
            keyong_tv.setText(NumberUtils.keepPrecision(getWalletEntityType("CSC").money,4) + " CSC");
        }

        TextView tv_duihuan = contentView.findViewById(R.id.tv_duihuan);//确认购买
        tv_duihuan.setText(viewModel.isBuy.getValue() ? "确认购买" : "确认转赠");
        tv_duihuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCustomPopWindow.dissmiss();

                double numStr = Double.parseDouble(model.entity.get().num);
                anquanYanzheng(view,viewModel.isBuy.getValue(), (int)numStr, model.entity.get().id+"");
            }
        });
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .setFocusable(true)
                .setOutsideTouchable(true)
//                .size(600,400) //设置显示的大小，不设置就默认包裹内容
                .size(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAtLocation(view, Gravity.BOTTOM,0,0);
//                .showAsDropDown(view,0,20);
    }


    private CustomPopWindow anquanYanzhengPopWindow;
    private void anquanYanzheng(View view,boolean isBuy, int num, String id)
    {
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.pop_anquan_yanzheng,null);
        EditText cede_et = contentView.findViewById(R.id.cede_et);
        EditText cede_yzm_et = contentView.findViewById(R.id.cede_yzm_et);
        EditText idcard_et = contentView.findViewById(R.id.idcard_et);
        TextView cancel_tv = contentView.findViewById(R.id.cancel_tv);
        RelativeLayout cede_yzm_rl = contentView.findViewById(R.id.cede_yzm_rl);
        if(isBuy)
        {
            cede_yzm_rl.setVisibility(View.GONE);
            idcard_et.setVisibility(View.GONE);
            cede_yzm_et.setVisibility(View.GONE);
        }
        cancel_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(anquanYanzhengPopWindow != null)
                {
                    anquanYanzhengPopWindow.dissmissNoRecovery();
                }
            }
        });
        TextView get_sms_code_tv = contentView.findViewById(R.id.get_sms_code_tv);
        get_sms_code_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModel.smsCode((TextView)view);
            }
        });
        TextView forget_tv = contentView.findViewById(R.id.forget_tv);
        forget_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(anquanYanzhengPopWindow != null)
                {
                    anquanYanzhengPopWindow.dissmissNoRecovery();
                }

                startContainerActivity(SafeFragment.class.getCanonicalName());
            }
        });
        TextView tv_queren = contentView.findViewById(R.id.tv_queren);
        tv_queren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(TextUtil.isEmpty(cede_et.getText().toString()))
                {
                    ToastUtil.showToast("请输入密码");
                    return;
                }
                if(!isBuy)
                {
                    if(TextUtil.isEmpty(idcard_et.getText().toString()))
                    {
                        ToastUtil.showToast("请输入身份证后六位");
                        return;
                    }
                    if(TextUtil.isEmpty(cede_yzm_et.getText().toString()))
                    {
                        ToastUtil.showToast("请输入验证码");
                        return;
                    }
                }
//                if(anquanYanzhengPopWindow != null)
//                {
//                    anquanYanzhengPopWindow.dissmissNoRecovery();
//                }

                viewModel.otcBuy(id,isBuy? "1" : "2",num+"", cede_et.getText().toString(),idcard_et.getText().toString(),cede_yzm_et.getText().toString());
            }
        });
        contentView.findViewById(R.id.content_rl).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(anquanYanzhengPopWindow != null)
                {
                    anquanYanzhengPopWindow.dissmissNoRecovery();
                }
            }
        });

        //创建并显示popWindow
        anquanYanzhengPopWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.3f) // 控制亮度
                .setFocusable(true)
                .setOutsideTouchable(true)
//                .size(600,400) //设置显示的大小，不设置就默认包裹内容
                .size(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAtLocation(view, Gravity.BOTTOM,0,20);
//                .showAsDropDown(view,0,20);
    }

    private WalletEntity getWalletEntityType(String type)
    {
        List<WalletEntity> walletEntities = ((AppApplication)AppApplication.getInstance()).getOtcWallet();
        if(walletEntities != null && walletEntities.size() > 0)
        {
            for(int i = 0; i < walletEntities.size(); i++)
            {
                WalletEntity mWalletEntity = walletEntities.get(i);
                if(mWalletEntity.coin_name.equals(type))
                {
                    return mWalletEntity;
                }
            }
        }
        return null;
    }
}